package com.wy.panda.interceptor;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 请求时长统计拦截器
 *
 * @author WangYuan
 * @since 2020年8月5日 下午8:09:02
 */
@Component
@Slf4j
public class ReqDurationStatisticsInterceptor extends HandlerInterceptorAdapter {
	
	private static final ThreadLocal<Long> START_TIME_THREAD_LOCAL = new ThreadLocal<>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.info("=====preHandle：{}", handler);
		
		START_TIME_THREAD_LOCAL.set(System.currentTimeMillis());
		
		List<String> values = Collections.list(request.getHeaderNames());
		String headers = values.stream().map(name -> name + ":" + Collections.list(request.getHeaders(name))).collect(Collectors.joining(", "));
		
		String params = request.getParameterMap().entrySet().stream()
				.map(entry -> entry.getKey() + ":" + Arrays.toString(entry.getValue()))
				.collect(Collectors.joining(", "));
		
		String queryString = request.getQueryString();
		String queryClause = (StringUtils.hasLength(queryString) ? "?" + queryString : "");
		String dispatchType = (!request.getDispatcherType().equals(DispatcherType.REQUEST) ?
				"\"" + request.getDispatcherType().name() + "\" dispatch for " : "");
		String message = (dispatchType + request.getMethod() + " \"" + getRequestUri(request) +
				queryClause + "\", parameters={" + params + "}");
		
		
		message = message + ", headers={" + headers + "} in DispatcherServlet";
		log.info(message);
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("=====afterCompletion");
		
		long endTime = System.currentTimeMillis();
		log.info("当前请求耗时（ms）：{}", endTime - START_TIME_THREAD_LOCAL.get());
	}
	
	private static String getRequestUri(HttpServletRequest request) {
		String uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
		if (uri == null) {
			uri = request.getRequestURI();
		}
		return uri;
	}

}
